package com.cma.service.impl;

import com.cma.model.db.SysUser;
import com.cma.dao.SysUserRepository;
import com.cma.service.SysUserService;

        import org.apache.commons.logging.Log;
        import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

        import java.util.ArrayList;
        import java.util.List;


/**
 * 系统用户表
 * 数据库表【sys_user】对应的service实现类
 *
 * @author  hbb
 * @date 2017-01-17 11:28:23
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    private static final Log logger = LogFactory.getLog(SysUserServiceImpl.class);

    @Autowired
    private SysUserRepository sysUserRepository;


    @PersistenceContext
    private EntityManager entityManager;


    //===================================================================================================

    /**
     * 保存或更新对象
     *
     * @param sysUser
     */
    @Override
    public void save(SysUser sysUser) {
        sysUserRepository.save(sysUser);
    }


    /**
         * 通过id查找对象
         *
         * @param id
         * @return
         */
    @Override
    public SysUser findById(Long id) {
        return sysUserRepository.findOne(id);
    }

    /**
     * 根据角色id 获取相对应的权限
     *
     * @param roleId
     * @return
     */
    @Override
    public String getPermissionsByRoleIds(String roleId) {
        String sql="SELECT a.menu_name,a.menu_desc FROM ma_menu a WHERE a.menu_id IN(SELECT b.menu_id FROM ma_role_menu_relation b WHERE b.role_id IN("+roleId+"))";
        Query query= entityManager.createNativeQuery(sql);
        String permissions="";
        List<Object[]> list=query.getResultList();
        // TODO 将权限表中该角色列表拥有的权限 取出来
        if(list!=null&&list.size()>0){
            for(int i=0;i<list.size();i++){
                if(permissions.length()>0){
                    // TODO 权限格式为： 权限名称1:权限描述1,权限名称2:权限描述2
                    // TODO 每一个权限中间以逗号隔开 组成权限字符串
                    permissions=permissions+","+list.get(i)[0]+":"+list.get(i)[1];
                }else {
                    permissions=list.get(i)[0]+":"+list.get(i)[1];
                }

            }
        }
        // TODO 返回该权限字符串
        return permissions;
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @Override
    public SysUser findByName(String username) {
        String sql="SELECT * FROM sys_user WHERE user_name='"+username+"'";
       Query query= entityManager.createNativeQuery(sql,SysUser.class);
        List<SysUser> list= query.getResultList();
        if(list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }


    /**
    * 提供给管理使用的分页查询
    *
    * @param pageable
    * @return
    */
    @Override
    public Page<SysUser> findForAdminList(Pageable pageable) {
        StringBuffer sqlForCount = new StringBuffer("select count(c.id) from SysUser c where 1=1 ");
        StringBuffer sqlForList = new StringBuffer("select c from SysUser c where 1=1 ");

        /*
        if (StringUtils.isNotBlank(name)) {
            sqlForCount.append(" and ( c.name like  '%" + name + "%' or c.username like '%" + name + "%' )  ");
            sqlForList.append(" and ( c.name like  '%" + name + "%' or c.username like '%" + name + "%' )  ");
        }
        */

        sqlForList.append(" order by c.id desc ");

        TypedQuery queryForCount = entityManager.createQuery(sqlForCount.toString(), Long.class);
        Long count = (Long) queryForCount.getSingleResult();

        TypedQuery queryForList = entityManager.createQuery(sqlForList.toString(), SysUser.class);
        List<SysUser> adminList = queryForList.setMaxResults(pageable.getPageSize()).setFirstResult(pageable.getOffset()).getResultList();

        Page<SysUser> pageRst = new PageImpl<SysUser>(adminList, pageable, count);
        return pageRst;
    }



}
